package com.dragonwu.im.server;

import com.dragonwu.im.constant.IMConstants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Dragon Wu
 * @since 2023/1/23 12:26
 * Netty IM的服务启动器
 */
@Component
public class IMServerStarter {

    @Value("${netty.port}")
    private Integer port;

    @Autowired
    @Qualifier("serverBootstrap")
    private ServerBootstrap serverBootstrap;

    private Channel channel;

    public void start() throws Exception {
        System.out.println("________                                         ___       __       \n" +
                "___  __ \\____________ _______ _____________      __ |     / /___  __\n" +
                "__  / / /_  ___/  __ `/_  __ `/  __ \\_  __ \\     __ | /| / /_  / / /\n" +
                "_  /_/ /_  /   / /_/ /_  /_/ // /_/ /  / / /     __ |/ |/ / / /_/ / \n" +
                "/_____/ /_/    \\__,_/ _\\__, / \\____//_/ /_/      ____/|__/  \\__,_/  \n" +
                "                      /____/                                        \n" +
                "                                            --Netty Successfully started!");
        System.out.println(IMConstants.HOST + port + IMConstants.WEBSOCKET_PATH);
        channel = serverBootstrap.bind(port).sync()
                .channel().closeFuture().sync().channel();
    }

    public void close() {
        channel.close();
        channel.parent().close();
    }
}
